//
//  SendOrderView.m
//  XRmenu-HD
//
//  Created by shengchao yang on 11-12-27.
//  Copyright (c) 2011年 home user. All rights reserved.
//

#import "SendOrderView.h"
#import "XRmenuHelper.h"
#import "Http.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"

#define kTagOfStartTextField      5760

@implementation SendOrderView
@synthesize pickerViewTables;
-(id) init{
    NSDictionary *vCfg = [APPSESSION.allconfig findAtPath:@"UIKit CSS/UIView CSS/send order view"];
	self = [super initWithConfig:vCfg];
    if (self) {
        UIColor *btn_color = RGBA(235.0, 217.0, 185.0, 254.0/ 255.0f);
        NSString *btn_bkg=[XRmenuPublic getGeneralSkinImg:@"MainView/MyOrderView/bt_myorder_main.png"];
        
        if ([self viewWithTag:kTagOfStartBT + 0]) {
            UIButton *btn =(UIButton *) [self viewWithTag:kTagOfStartBT + 0];
            [btn.titleLabel setFont:[UIFont fontWithName:@"Arial" size:20]];
            [btn setTitle:loc(@"发送") forState:UIControlStateNormal];
            [btn setTitleColor:btn_color forState:UIControlStateNormal];
            [btn setBackgroundImage:[UIImage imageWithContentsOfFile:btn_bkg] forState:UIControlStateNormal];
        }
        if ([self viewWithTag:kTagOfStartBT + 1]) {
            UIButton *btn =(UIButton *) [self viewWithTag:kTagOfStartBT + 1];
            [btn.titleLabel setFont:[UIFont fontWithName:@"Arial" size:20]];
            [btn setTitle:loc(@"返回") forState:UIControlStateNormal];
            [btn setTitleColor:btn_color forState:UIControlStateNormal];
            [btn setBackgroundImage:[UIImage imageWithContentsOfFile:btn_bkg] forState:UIControlStateNormal];
        }
        //初始化两个textfield
        UITextField *fieldUsername=[[UITextField alloc] initWithFrame:CGRectMake(130, 25, 320, 35)];
        [fieldUsername setBorderStyle:UITextBorderStyleNone];
        [fieldUsername setBackgroundColor:[UIColor whiteColor]];
        [fieldUsername setPlaceholder:loc(@"输入工号")];
        [fieldUsername setFont:[UIFont fontWithName:[[UIFont fontNamesForFamilyName:@"Arial"] objectAtIndex:1] size:25]];
        [fieldUsername setClearButtonMode:UITextFieldViewModeWhileEditing];
        [fieldUsername setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
        [fieldUsername setTag:kTagOfStartTextField];
        [self addSubview:fieldUsername];
        [fieldUsername release];
        
        UITextField *fieldPassword=[[UITextField alloc] initWithFrame:CGRectMake(130, 70, 320, 35)];
        [fieldPassword setBorderStyle:UITextBorderStyleNone];
        [fieldPassword setBackgroundColor:[UIColor whiteColor]];
        [fieldPassword setPlaceholder:loc(@"输入密码")];
        [fieldPassword setFont:[UIFont fontWithName:[[UIFont fontNamesForFamilyName:@"Arial"] objectAtIndex:1] size:25]];
        [fieldPassword setClearButtonMode:UITextFieldViewModeWhileEditing];
        [fieldPassword setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
        [fieldPassword setTag:kTagOfStartTextField + 1];
        [fieldPassword setSecureTextEntry:YES];//密码
        [self addSubview:fieldPassword];
        [fieldPassword release];
        
        //初始化桌号
        pickerViewTables = [[UIPickerView alloc] initWithFrame:CGRectMake(130, 140, 320, 162)];
        [pickerViewTables setDelegate:self];
        [pickerViewTables setDataSource:self];
        [pickerViewTables setShowsSelectionIndicator:YES];
        [self addSubview:pickerViewTables];
    }
    return self;
}

#pragma mark 重载button处理方法
-(void) buttonClicked:(id)sender
{
	NSInteger bid = [sender tag];
    if (bid == (kTagOfStartBT + 0)) {        
        DebugLog(@"点击了送单按钮");
        [APPSESSION playSoundOnEvent:[XRmenuPublic getGeneralSkinImg:@"buttonClicked.caf"]];
        NSString *empno=((UITextField *)[self viewWithTag:kTagOfStartTextField]).text;
        NSString *password=((UITextField *)[self viewWithTag:kTagOfStartTextField+1]).text;
        if (password==nil) {
            password=@"";
        }
        NSInteger persons=[pickerViewTables selectedRowInComponent:1]+1;
        if (empno==nil || [empno length]==0) {
            UIAlertView *alert =[[ UIAlertView alloc] initWithTitle:loc(@"提示") 
                                                            message:loc(@"输入工号")
                                                           delegate:self 
                                                  cancelButtonTitle:loc(@"确定") 
                                                  otherButtonTitles:nil];
            [alert show];
            [alert release];
        }
        else if ([APPSESSION.allTables count]==0) {
            UIAlertView *alert =[[ UIAlertView alloc] initWithTitle:loc(@"提示") 
                                                            message:loc(@"没有桌号")
                                                           delegate:self 
                                                  cancelButtonTitle:loc(@"确定") 
                                                  otherButtonTitles:nil];
            [alert show];
            [alert release];
        }
        else{
            NSInteger tableRow=[pickerViewTables selectedRowInComponent:0];
            PluTable *selectedTable=(PluTable *)[APPSESSION.allTables objectAtIndex:tableRow];
            DebugLog(@"tableno=%@,tableName=%@",selectedTable.ptTableNo, selectedTable.ptDescripts);
            
            NSString *sendOrderJson=[NSString stringWithFormat:@"{\"empno\":\"%@\",\"password\":\"%@\",\"persons\":\"%d\",\"tableno\":\"%@\",\"UDID\":\"%@\",\"myorders\":",empno,password,persons,selectedTable.ptTableNo,APPSESSION.udid];
            
            //组装我的点单json串
            NSString *myorderJson=@"[";
            int indexMyOrder=0;
            for (DishOrder *oneorder in APPSESSION.myOrders) {
                indexMyOrder++;
                if (oneorder.ddRemark==nil) {
                    myorderJson=[myorderJson stringByAppendingFormat:@"{\"ddRemark\":\"%@\",",@""];
                }
                else{
                    myorderJson=[myorderJson stringByAppendingFormat:@"{\"ddRemark\":\"%@\",",oneorder.ddRemark];
                }
                myorderJson=[myorderJson stringByAppendingFormat:@"\"ddCode\":\"%@\",",oneorder.ddCode];
                myorderJson=[myorderJson stringByAppendingFormat:@"\"ddNumber\":\"%d\"}",[oneorder.ddNumber intValue]];
                if (indexMyOrder<[APPSESSION.myOrders count]) {
                    myorderJson=[myorderJson stringByAppendingFormat:@","];
                }
            }
            myorderJson=[myorderJson stringByAppendingFormat:@"]"];
            sendOrderJson=[sendOrderJson stringByAppendingFormat:@"%@}",myorderJson];//最终要发送的json串
            sendOrderJson=[sendOrderJson stringByReplacingOccurrencesOfString:@"\t" withString:@""];//去掉特殊符
            sendOrderJson=[sendOrderJson stringByReplacingOccurrencesOfString:@"\r" withString:@""];//去掉特殊符
            sendOrderJson=[sendOrderJson stringByReplacingOccurrencesOfString:@"\n" withString:@""];//去掉特殊符
            DebugLog(@"sendOrderJson=%@", sendOrderJson);
            XRmenuError *outError = nil;
            NSString *sendResult=[XRmenuHelper sendMyOrders:sendOrderJson Error:&outError];
            if (![sendResult isContainsString:@"true"]) {
                NSDictionary *resultDic=[sendResult JSONValue];
                NSString *errCode=@"";
                NSString *errMsg=@"";
                DebugLog(@"发送我的点单出错!sendResult=%@",sendResult);     
                if ([resultDic count]==0) {
                    errCode=@"9999";
                    errMsg=[NSString stringWithFormat:@"%@\r\n%@",[outError localizedDescription],sendResult];
                }
                else{
                    errCode=[resultDic objectForKey:@"code"];
                    errMsg=[resultDic objectForKey:@"message"];
//                    errMsg=[[resultDic objectForKey:@"message"] UTF8DecodedString];//UTF8解码
                }
                UIAlertView *alert =[[ UIAlertView alloc] initWithTitle:loc(@"送单错误")
                                                                message:[NSString stringWithFormat:@"(%@)%@",errCode,errMsg]
                                                               delegate:self 
                                                      cancelButtonTitle:loc(@"确定")
                                                      otherButtonTitles:nil];
                [alert show];
                [alert release];
            }
            else{
                DebugLog(@"送单成功！");
                //删除我的点单数据
                XRmenuError *outErr=nil;
                [XRmenuCoreData deleteAllDishOrder:&outErr];
                [APPSESSION getAllMyOrder];
                //1.界面上更新我的点单数量
                postN(kMessage_MainView_MyOrderNumberChanged);
                postN(kMessage_CommendTable_MyOrderNumberChanged);
                //2.刷新我的点单table
                postN(kMessage_MyOrderView_ReloadTableViewData);
                //3.退出送单界面 
                postN(kMessage_RootView_SendOrderViewDisappear);
            }
        }
	}
    else if (bid == (kTagOfStartBT + 1)) {        
        DebugLog(@"点击了返回按钮");
        [APPSESSION playSoundOnEvent:[XRmenuPublic getGeneralSkinImg:@"buttonClicked.caf"]];
        postN(kMessage_RootView_SendOrderViewDisappear);
	}
}

#pragma mark -
#pragma mark picker 数据源方法

//选取器如果有多个滚轮，就返回滚轮的数量，我们这里有两个，就返回2
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
	return 2;
}
//返回给定的组件有多少行数据，我们有2个组件，所以用if操作。后期tableview也是类似的操作方法
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component==0) {
        return [APPSESSION.allTables count];
    }
	else{
        return 50;
    }
}

#pragma mark -
#pragma mark picker 委托方法

//官方的意思是，指定组件中的指定数据，我理解的就是目前选中的是哪一行。
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component==0) {
        return JsonFiled(((PluTable *)[APPSESSION.allTables objectAtIndex:row]).ptDescripts);
    }
	else{
        return [NSString stringWithFormat:@"%d",row+1];
    }
}

//当选取器的行发生改变的时候调用这个方法
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{

}

//=========================================================== 
// dealloc
//=========================================================== 
- (void)dealloc
{
    [pickerViewTables release];
    pickerViewTables=nil;
    [super dealloc];
}
@end
